package com.huatai.bimonitor.config;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.client.naming.NacosNamingService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huatai.bimonitor.entity.MqClientNumberEntity;
import com.huatai.bimonitor.entity.MqMqttClientEntity;
import com.huatai.bimonitor.service.MqClientNumberService;
import com.huatai.bimonitor.service.MqMqttClientService;
import com.huatai.common.util.CollectionUtil;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @program: ganghua
 * @description: 监控BI服务运行情况
 * @author: songxiude
 * @create: 2024-09-05 15:32
 **/
@Component
public class MonitorRunner implements CommandLineRunner {
	/**
	 * 获取nacos属性配置信息
	 */
	@Autowired
	private NacosDiscoveryProperties nacosDiscoveryProperties;

	@Autowired
	private MqClientNumberService numberService;

	@Autowired
	private MqMqttClientService clientService;

	@Autowired
	private RabbitTemplate rabbitTemplate;

	/**
	 * 每5秒检测一次服务状态并处理mqtt链接状态
	 *
	 * @param args
	 * @throws Exception
	 */
	@Override
	public void run(String... args) throws Exception {
		NacosNamingService nacosNamingService = new NacosNamingService(nacosDiscoveryProperties.getNacosProperties());
		new Thread(() -> {
			while (true) {
				try {

					//5秒执行一次
					Thread.sleep(5000);
					// 获取服务名称为testdemo的服务列表信息

					List<Instance> instances = nacosNamingService.getAllInstances("bi");
					//long count = numberService.count(Wrappers.<MqClientNumberEntity>lambdaQuery().eq(MqClientNumberEntity::getIsActive, 1));
					int serviceCount = instances.size();
					System.out.println("真实实例:" + serviceCount);
					//如果没有实例更新数据状态
					if (serviceCount == 0) {
						numberService.update(null, Wrappers.<MqClientNumberEntity>lambdaUpdate().set(MqClientNumberEntity::getIsActive, 0).set(MqClientNumberEntity::getClientNumber, 0));
					}else {
						List<String> list = new ArrayList<>();
						for (Instance instance : instances) {
							list.add(instance.getIp() + ":" + instance.getPort());
						}
						List<MqClientNumberEntity> entityList = numberService.list(Wrappers.<MqClientNumberEntity>lambdaQuery().notIn(MqClientNumberEntity::getIpPort, list).eq(MqClientNumberEntity::getIsActive, 1));

						//如果某实例掉线更改状态
						if (CollectionUtil.isNotEmpty(entityList)) {

							List<MqClientNumberEntity> numberEntities = numberService.list(Wrappers.<MqClientNumberEntity>lambdaQuery().notIn(MqClientNumberEntity::getIpPort, list));
							numberService.update(null, Wrappers.<MqClientNumberEntity>lambdaUpdate()
								.notIn(MqClientNumberEntity::getIpPort, list).set(MqClientNumberEntity::getIsActive, 0).set(MqClientNumberEntity::getClientNumber, 0));

							clientService.update(null, Wrappers.<MqMqttClientEntity>lambdaUpdate()
								.notIn(MqMqttClientEntity::getIpPort, list).set(MqMqttClientEntity::getStatus, 0));

							rabbitTemplate.convertAndSend("serverExchange", "", JSONObject.toJSONString(numberEntities));
						}
					}


				} catch (InterruptedException e) {
					e.printStackTrace();
				} catch (NacosException e) {
					e.printStackTrace();
				}
			}
		}).start();
	}
}
